package com.sam.im.heiqun.uis.activities;

import android.content.Context;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.entities.MsgEntity;
import com.sam.im.heiqun.uis.adapters.ChatRecyclerAdapter;
import com.sam.im.heiqun.utils.ConversationUtils;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.yuyh.library.uis.activitys.BaseActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Timer;
import java.util.TimerTask;

public class CallFriendActivity extends BaseActivity implements View.OnClickListener {

    private LinearLayout ll_call_callResponse;
    private TextView tv_ca_name;
    private Button btn_canale_video, btn_agree_vido;
    private ConversationUtils conversationUtils;
    private long destid;
    private String type;//voice 语音 video视频
    private boolean isLive = false;

    @Override
    public int getContentViewId() {
        return R.layout.activity_call_friend;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        isLive = true;
        EventBus.getDefault().register(this);
        ll_call_callResponse = (LinearLayout) findViewById(R.id.ll_call_callResponse);
        btn_canale_video = (Button) findViewById(R.id.btn_canale_video);
        btn_agree_vido = (Button) findViewById(R.id.btn_agree_vido);
        tv_ca_name = (TextView) findViewById(R.id.tv_ca_name);
        destid = getIntent().getLongExtra("destid", 0);
        type = getIntent().getStringExtra("type");
        SharedPreferences.Editor editor = getSharedPreferences("Demo", Context.MODE_PRIVATE).edit();
        editor.putString("friend_ids", destid + "");
        editor.commit();

        ll_call_callResponse.setVisibility(View.GONE);
        btn_canale_video.setOnClickListener(this);
        btn_agree_vido.setOnClickListener(this);
        conversationUtils = new ConversationUtils(this);
        //开视频
        callFreind();
        time();
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onBaseEvent(final Integer type) {
        if (type == com.sam.im.heiqun.constant.Constant.TOMessageTypeRefuseVideoRequest) {
            mPlayer.stop();
            finish();
        }
    }

    Timer timer = new Timer();

    /**
     * 计时
     */
    public void time() {
        timer.schedule(task, 1000, 1000);
    }

    private int recLen = 0;
    TimerTask task = new TimerTask() {
        @Override
        public void run() {

            runOnUiThread(new Runnable() {      // UI thread
                @Override
                public void run() {

                    ++recLen;
                    if (recLen < 0) {
                        timer.cancel();
                    }
                    if (recLen >= 10 && isLive) {
                        timer.cancel();
                        mPlayer.stop();
                        cancleVideo("", Constant.TOMessageTypeCancleVoiceVideo);
                        MsgEntity  msgEntity = new MsgEntity();
                        msgEntity.setMsgString(getResources().getString(R.string.chat_cancle));
                        String msg = new Gson().toJson(msgEntity);
                        conversationUtils.sendMsgTime(msg, ChatRecyclerAdapter.TO_USER_EMOJI_TEXT, (int) destid);
                        finish();
                    }

                }
            });
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_canale_video:
                //挂断
                mPlayer.stop();
                cancleVideo("", Constant.TOMessageTypeCancleVoiceVideo);
                MsgEntity  msgEntity = new MsgEntity();
                msgEntity.setMsgString(getResources().getString(R.string.chat_cancle));
                String msg = new Gson().toJson(msgEntity);
                conversationUtils.sendMsgTime(msg, ChatRecyclerAdapter.TO_USER_EMOJI_TEXT, (int) destid);
                finish();
                break;

            default:
                break;
        }
    }

    public void cancleVideo(String data, int type) {
        MsgEntity msgEntity = new MsgEntity();
        msgEntity.setMsgString(data);
        String msg = new Gson().toJson(msgEntity);
        conversationUtils.sendMsg(msg, type, (int) destid);
    }

    private MediaPlayer mPlayer;

    public void callFreind() {
        if (type.equals("voice")) {
            //语音
            conversationUtils.sendMsg(System.currentTimeMillis() + ToolsUtils.getMyUserId(), Constant.TOMessageTypeVoiceRequest, (int) destid);
        } else if (type.equals("video")) {
            //视频
            conversationUtils.sendMsg(System.currentTimeMillis() + ToolsUtils.getMyUserId(), Constant.TOMessageTypeVideoRequest, (int) destid);
        }
        //开启发起语音

        mPlayer = MediaPlayer.create(this, R.raw.music_calllink);
        mPlayer.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isLive = false;
        timer.cancel();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            MsgEntity msgEntity = new MsgEntity();
            msgEntity.setMsgCodes("");
            msgEntity.setMsgString("");
            msgEntity.setMsgType("");
            String msg = new Gson().toJson(msgEntity);

            conversationUtils.sendMsg(msg, Constant.TOMessageTypeCancleVoiceVideo, (int) destid);
            mPlayer.stop();
            finish();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }

    }
}
